package cat.joronya.supermanager.home;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.drawer.DrawerActivity;
import cat.joronya.supermanager.drawer.DrawerItem;
import cat.joronya.supermanager.home.HomeFragment.OnAboutListener;
import cat.joronya.supermanager.market.MarketListActivity;
import cat.joronya.supermanager.market.PagerAdapter;
import cat.joronya.supermanager.privateleague.PrivateLeagueListActivity;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.service.UserDataManager;
import cat.joronya.supermanager.team.MyTeamsListActivity;

public class HomeActivity extends DrawerActivity 
	implements OnAboutListener, TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener
{
	public static final String TAG = "Supervermut";
	
	private TabHost mTabHost;
	private ViewPager mViewPager;
    private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, HomeActivity.TabInfo>();
    private PagerAdapter mPagerAdapter;
    
    private List<Fragment> mFragments;
	
    private class TabInfo 
    {
        private String tag;
        private Class<?> clss;
        private Bundle args;
        private Fragment fragment;
        TabInfo(String tag, Class<?> clazz, Bundle args) 
        {
            this.tag = tag;
            this.clss = clazz;
            this.args = args;
        }
    }
    
    class TabFactory implements TabContentFactory 
    {
        private final Context mContext;
 
        /**
         * @param context
         */
        public TabFactory(Context context) {
            mContext = context;
        }
 
        /** (non-Javadoc)
         * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
         */
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	// set layout and call super onCreate
    	setmLayoutResource(R.layout.market_drawer_layout);
    	setmLayoutId(R.id.drawer_layout);
    	super.onCreate(savedInstanceState);
    	
    	// Initialise the TabHost
        this.initialiseTabHost(savedInstanceState);
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state
        }
        // Intialise ViewPager
        this.intialiseViewPager();
        
        // titol de la pantalla home inicalment
        setTitle(getResources().getString(R.string.home_tab));
        
        // en background fem el check
        new Thread(){
        	public void run(){
        		// perform check, if we're up to date then dismiss and continue
        		if( !UserDataManager.appNeedsUpdate(HomeActivity.this) )
        		{
        			Log.d(TAG,"HomeActivity userDataManager: app doesn't need update");
        			return;
        		}
        		
        		Log.d(TAG,"HomeActivity userDataManager: app needs update!");
        		
        		// cridar refresh al REST method
           		SupermanagerServiceHelper.getInstance(HomeActivity.this).fullUpdate(null, true);
        	}
        }.start();
    } 
    
    @Override
    protected void onNewIntent(Intent intent) 
    {
    	super.onNewIntent(intent);
    	
        // Initialise the TabHost
        this.initialiseTabHost(new Bundle());

        // Intialise ViewPager
        this.intialiseViewPager();
        
    	setTitle(getResources().getString(R.string.home_tab));
    }
    
    /** (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
     */
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
        super.onSaveInstanceState(outState);
    }
    
    protected String getDay()
    {
    	Cursor cursor = getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION, 
           		null,
           		null,
                Supermanager.Home.DEFAULT_SORT_ORDER);
    	
    	int day = 0;
    	if( cursor.moveToFirst() )
    		day = cursor.getInt(5);
    	
    	cursor.close();
    	return day+"";
    }
    
    /**
     * Initialise ViewPager
     */
    private void intialiseViewPager() 
    {
    	if( mFragments != null )
    		return;
    	
        mFragments = new Vector<Fragment>();
        
        mFragments.add(new HomeFragment());
        mFragments.add(NextMatchesListFragment.newInstance(getDay()));
        
        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), mFragments);
        //
        this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager);
        this.mViewPager.setAdapter(this.mPagerAdapter);
        this.mViewPager.setOnPageChangeListener(this);
    }
    
    /**
     * Initialise the Tab Host
     */
    private void initialiseTabHost(Bundle args) 
    {
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();
        TabInfo tabInfo = null;
        
        if( mTabHost.getTabWidget().getTabCount() > 0 )
        	return;
        
        HomeActivity.AddTab(this, 
        		this.mTabHost, 
        		this.mTabHost.newTabSpec("supermanager").setIndicator(getString(R.string.home_supermanager_tab)), ( 
        				tabInfo = new TabInfo("supermanager", HomeFragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        HomeActivity.AddTab(this, 
        		this.mTabHost, 
        		this.mTabHost.newTabSpec("nextmatches").setIndicator(getString(R.string.home_nextmatches_tab)), ( 
        				tabInfo = new TabInfo("nextmatches", NextMatchesListFragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        
        mTabHost.setOnTabChangedListener(this);
    }
    
    /**
     * Add Tab content to the Tabhost
     */
    private static void AddTab(HomeActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) 
    {
        // Attach a Tab view factory to the spec
        tabSpec.setContent(activity.new TabFactory(activity));
        tabHost.addTab(tabSpec);
    }
 
    /** (non-Javadoc)
     * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
     */
    public void onTabChanged(String tag) 
    {
        //TabInfo newTab = this.mapTabInfo.get(tag);
        int pos = this.mTabHost.getCurrentTab();
        this.mViewPager.setCurrentItem(pos);
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled(int, float, int)
     */
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 
    {
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected(int)
     */
    public void onPageSelected(int position) 
    {
        this.mTabHost.setCurrentTab(position);
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
     */
    public void onPageScrollStateChanged(int state) 
    {
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
    	Log.d(TAG,"SupermanagerActivity.onConfigurationChanged called");
		
		// actualitzem dades
    	super.onConfigurationChanged(newConfig);
    }
    
    protected DrawerItem[] getDrawerItems()
    {
    	mDrawerTitles = getResources().getStringArray(R.array.drawer_titles);
        mDrawerIcons = getResources().getStringArray(R.array.drawer_icons);
        
    	DrawerItem[] items = new DrawerItem[mDrawerTitles.length];
    	for(int i=0; i<mDrawerTitles.length; i++)
    	{
    		int icon = getResources().getIdentifier(mDrawerIcons[i], "drawable", this.getPackageName());
    		items[i] = DrawerItem.create(mDrawerTitles[i], icon);
    	}
    	
    	return items;
    }
        
    /** 
     * Swaps fragments in the main content view 
     */
    protected void selectItem(int position) 
    {
    	setTitle(mDrawerTitles[position]);
    	Log.d(TAG,"selectItem on drawer");
    	
    	switch(position) 
    	{
			case 0:
				
				break;
			case 1:
				// private league list activity
				Intent privateLeagueListActivity = new Intent(getBaseContext(), PrivateLeagueListActivity.class);
        		startActivity(privateLeagueListActivity);
        		overridePendingTransition(0,0);
				break;
			case 2:
				// market list activity
				Intent marketListActivity = new Intent(getBaseContext(), MarketListActivity.class);
        		startActivity(marketListActivity);
        		overridePendingTransition(0,0);
        		break;
			case 3:
				// my teams list activity
				Intent myteamsListActivity = new Intent(getBaseContext(), MyTeamsListActivity.class);
				startActivity(myteamsListActivity);
				overridePendingTransition(0,0);
				break;
			default:
				
				break;
		}
    	
    	mDrawerLayout.closeDrawer(mDrawerList);
    }

	public void showAboutDialog() 
	{
		AboutDialogFragment newFragment = AboutDialogFragment.newInstance();
	    newFragment.show(getSupportFragmentManager(), "about_dialog");
	}
	
	// click al about del dialeg
	public void openLink(View view) 
	{
		// throw CONTENT_URI of web
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(getString(R.string.about_link)));
		startActivity(i);
	}
}
